package com.wxs.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.xml.ws.RequestWrapper;

@Controller
public class MyController {

    @RequestMapping({"/","/index"})
    public String index(Model model){
        model.addAttribute("msg","hello Shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String addUser(){
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String updateUser(){
        return "user/update";
    }


    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username, String password, Model model) { /*for认证*/
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登陆数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try{
            subject.login(token);
            return "index";
        }catch (UnknownAccountException uae){ /*用户名不存在*/
            model.addAttribute("msg","There is no user with username of " + token.getPrincipal());
            return "login";
        } catch (IncorrectCredentialsException ice) { /*密码错误*/
            model.addAttribute("msg","Password for account " + token.getPrincipal() + " was incorrect!");
            return "login";
        }

    }


    }
